package com.feiyuan.admin.app.controller;

import com.feiyuan.common.annotation.Login;
import com.feiyuan.common.annotation.LoginUser;
import com.feiyuan.common.entity.UserEntity;
import com.feiyuan.common.utils.R;
import com.feiyuan.common.validator.ValidatorUtils;
import com.feiyuan.admin.app.form.LoginForm;
import com.feiyuan.admin.app.service.UserService;
import com.feiyuan.admin.app.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * APP登录授权
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("/app")
@Api("APP登录接口")
public class AppLoginController {
    @Autowired
    private UserService userService;
    @Autowired
    private JwtUtils jwtUtils;

    /**
     * 发送验证码
     */
    @PostMapping("/sendCode")
    public R sendCode(@RequestBody LoginForm form) {
        if (StringUtils.isBlank(form.getMobile())) {
            return R.error(500, "手机号不能为空!");
        }
        Boolean isSuccess = userService.sendCode(form.getMobile());
        return R.ok().put("isSuccess", isSuccess);
    }

    /**
     * 登录
     */
    @PostMapping("/login")
    @ApiOperation("登录")
    public R login(@RequestBody LoginForm form){
        //表单校验
        ValidatorUtils.validateEntity(form);

        //用户登录
//        long userId = userService.login(form);

        Map<String, Object> map = userService.newLogin(form);

        //生成token
//        String token = jwtUtils.generateToken(userId);
//
//        Map<String, Object> map = new HashMap<>();
//        map.put("token", token);
//        map.put("expire", jwtUtils.getExpire());

        return R.ok(map);
    }

    @PostMapping("/logout")
    @ApiOperation("退出登录")
    @Login
    public R logout(@LoginUser UserEntity user, HttpServletRequest request) {
        Boolean isSuccess = userService.logout(user.getMobile(), request);
        return R.ok().put("isLogout", isSuccess);
    }

}
